package com.engine.budget.cmd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;

import java.time.Year;
import java.util.*;

/**
 * @author 祖梦杰
 * @version 1.0
 * @date 2024/7/26
 * @description: 营销项目启动及调整接口
 */
public class MarketProjectEnable extends AbstractCommonCommand<Map<String, Object>> {

    int nowYear = Year.now().getValue();


    public MarketProjectEnable(User user, Map<String, Object> params) {
        this.user = user;
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    Map<String, Object> createrequestMap = new HashMap<>();

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {


        //4.定义SQL语句
        String sql = "SELECT t1.id, t1.workflowname, t2.tablename FROM workflow_base t1 LEFT JOIN workflow_bill t2 ON t1.FORMID = t2.id WHERE t1.id = ? ";


        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, Prop.getPropValue("businessbudgetpz", "marketProjectWorkFlowId"));

        while (rs.next()) {
            createrequestMap.put("workflowid", rs.getString("id"));
            createrequestMap.put("title", rs.getString("workflowname"));
            createrequestMap.put("tableName", rs.getString("tablename"));
        }


        String data = params.get("data").toString();
        logger.info("data=" + data);
        JSONObject paramData = JSONObject.parseObject(data);
        String instruct = paramData.getString("instruct");
        Map<String, Object> map = new HashMap<>();
        if ("QY".equals(instruct)) {
            qd(paramData);
        } else if ("XXTZ".equals(instruct)) {
            xxtz(paramData);
        }
//        }else if("TZ".equals(data.get("instruct"))){
//            tz(data);
//        }else if("TJ".equals(data.get("instruct"))){
//            tj(data);
//        }else if("JY".equals(data.get("instruct"))){
//            jy(data);
//        }
        map.put("data", "[{}]");
        return map;
    }

    /**
     * 非金额信息调整入口
     *
     * @param paramData
     */
    private void xxtz(Map<String, Object> paramData) {
        Map<String, Object> map = new HashMap<>();


        RecordSet xmbmRs = new RecordSet();
        String projectNumber = (String) paramData.get("projectNumber");
        if (projectNumber != null && !projectNumber.isEmpty()) {
            xmbmRs.executeQuery("select id FROM uf_ysxmdb WHERE xmbm = ?  ", projectNumber);
            while (xmbmRs.next()) {
                map.put("xmbh", xmbmRs.getString("id"));
            }
        }
        logger.info("项目编码:"+map.get("xmbh"));

        String id = null;
        RecordSet recordSet1 = new RecordSet();
        recordSet1.executeQuery("select id from "+createrequestMap.get("tableName")+" where xmbh = ? ",map.get("xmbh"));
        while (recordSet1.next()) {
            id = recordSet1.getString("id");
            map.put("id",id);
        }



        //修改数据
        RecordSet recordSet = new RecordSet();
        String sql = "UPDATE "+createrequestMap.get("tableName")+" SET sqdh=?,sqsj=?,yszz=?,xmmc=?,qbhhhyjyd=?,qbmchhyjyd=?,xmzbrmc=?,xmzbrgh=?,ywlx=?,ywxl=?,xmqdsj=?,xmjssj=?,xmlxzjewy=?,czfs=?,ylzd=?,qbfwdz=?,fafwdz=?,gxsj=?,xmbh=?,kmbm=?,ysnd=? WHERE  id= "+id;



        RecordSet yszzRs = new RecordSet();
        String executeDept = (String) paramData.get("executeDept");
        if (executeDept != null && !executeDept.isEmpty()) {
            yszzRs.executeQuery("select * FROM uf_jccs_yszrzx WHERE yszrzxbm = ? ", executeDept);
            while (yszzRs.next()) {
                map.put("yszz", yszzRs.getString("id"));
            }
        }


        RecordSet ywlxRs = new RecordSet();
        RecordSet yskmRs = new RecordSet();
        String itemType = (String) paramData.get("itemType");
        if (itemType != null && !itemType.isEmpty()) {
            ywlxRs.executeQuery("select * FROM uf_jccs_ysxmywlx WHERE ysywlxbm = ?  ", itemType);
            while (ywlxRs.next()) {
                map.put("ywlx", ywlxRs.getString("id"));
            }
            yskmRs.executeQuery("SELECT yskmbm FROM uf_jccs_yskmysxmywl WHERE ysxmywlxbm = ? ", itemType);
            while (yskmRs.next()) {
                map.put("kmbm", yskmRs.getString("yskmbm"));
            }
        }

        RecordSet ywxlRs = new RecordSet();
        String itemDetail = (String) paramData.get("itemDetail");
        if (itemDetail != null && !itemDetail.isEmpty()) {
            ywxlRs.executeQuery("select * FROM uf_jccs_ysxmywlx WHERE ysywlxbm = ? ", itemDetail);
            while (ywxlRs.next()) {
                map.put("ywxl", ywxlRs.getString("id"));
            }

        }

        map.put("ysnd", nowYear);
        map.put("sqdh", Util.null2String(paramData.get("requestNo")));
        map.put("sqsj", Util.null2String(paramData.get("requestTime")));
        map.put("xmmc", Util.null2String(paramData.get("projectName")));
        map.put("qbhhhyjyd", Util.null2String(paramData.get("signReportNum")));
        map.put("qbmchhyjyd", Util.null2String(paramData.get("signReportName")));
        map.put("xmzbrmc", Util.null2String(paramData.get("userName")));
        map.put("xmzbrgh", Util.null2String(paramData.get("userNumber")));
        map.put("xmqdsj", Util.null2String(paramData.get("startTime")));
        map.put("xmjssj", Util.null2String(paramData.get("endOfTime")));
        map.put("xmlxzjewy", Util.null2String(paramData.get("projectTotalAmount")));
        map.put("czfs", Util.null2String(paramData.get("investmentType")));
        map.put("ylzd", Util.null2String(paramData.get("attribute3")));
        map.put("qbfwdz", Util.null2String(paramData.get("signReportURL")));
        map.put("fafwdz", Util.null2String(paramData.get("optionURL")));
        map.put("gxsj", Util.null2String(paramData.get("updateDate")));


        int index = 0;
        List<Object> data = new ArrayList<>();
        data.add(Util.null2String(map.get("sqdh")));
        data.add(Util.null2String(map.get("sqsj")));
        data.add(Util.null2String(map.get("yszz")));
        data.add(Util.null2String(map.get("xmmc")));
        data.add(Util.null2String(map.get("qbhhhyjyd")));
        data.add(Util.null2String(map.get("qbmchhyjyd")));
        data.add(Util.null2String(map.get("xmzbrmc")));
        data.add(Util.null2String(map.get("xmzbrgh")));
        data.add(Util.null2String(map.get("ywlx")));
        data.add(Util.null2String(map.get("ywxl")));
        data.add(Util.null2String(map.get("xmqdsj")));
        data.add(Util.null2String(map.get("xmjssj")));
        data.add(Util.null2String(map.get("xmlxzjewy")));
        data.add(Util.null2String(map.get("czfs")));
        data.add(Util.null2String(map.get("ylzd")));
        data.add(Util.null2String(map.get("qbfwdz")));
        data.add(Util.null2String(map.get("fafwdz")));
        data.add(Util.null2String(map.get("gxsj")));
        data.add(Util.null2String(map.get("xmbh")));
        data.add(Util.null2String(map.get("kmbm")));
        data.add(Util.null2String(map.get("ysnd")));
        logger.info("营销启动调整任务新增比较....data=" + data + "..params=" + map+"...sql="+sql );
        boolean b = recordSet.executeUpdate(sql, data);
        logger.info("营销启动调整任务新增...flag=" + b);


        //修改从表
        RecordSet rs = new RecordSet();
        boolean deleteFlagDt1 = rs.executeUpdate("DELETE FROM " + createrequestMap.get("tableName") + "_dt1 WHERE mainid = ?", id);
        addDt1(id);
        logger.info("从表1删除...flag=" + deleteFlagDt1);
        boolean deleteFlagDt2 = rs.executeUpdate("DELETE FROM " + createrequestMap.get("tableName") + "_dt2 WHERE mainid = ?", id);
        addDt2(id);
        logger.info("从表2删除...flag=" + deleteFlagDt2);



        //修改项目底表
        ArrayList<Object> datas = new ArrayList<>();
        datas.add(Util.null2String(map.get("xmmc")));
//        data.add(Util.null2String(map.get("qbhhhyjyd")));
        datas.add(Util.null2String(map.get("qbmchhyjyd")));
        datas.add(Util.null2String(map.get("xmzbrmc")));
        datas.add(Util.null2String(map.get("xmzbrgh")));
        datas.add(Util.null2String(itemDetail));
        datas.add(Util.null2String(itemType));
        datas.add(Util.null2String(map.get("xmqdsj")));
        datas.add(Util.null2String(map.get("xmjssj")));
        datas.add(Util.null2String(map.get("xmlxzjewy")));
        datas.add(Util.null2String(map.get("xmlxzjewy")));
        ArrayList<Object> datasDt1 = new ArrayList<>();
        datasDt1.add(Util.null2String(map.get("kmbm")));
        datasDt1.add(Util.null2String(map.get("ysnd")));

        rs.executeUpdate("UPDATE uf_ysxmdb SET xmmc=?,qbmc=?,xmzbrmc=?,xmzbrgh=?,ywlx=?,ywxl=?,xmqdsj=?,xmjssj=?,xmlxzjewy=? WHERE xmbm = "+map.get("xmbh"),datas);

        rs.executeUpdate("UPDATE uf_ysxmdb_dt1 SET yskm=? ,ysnd=? WHERE mainid = "+map.get("xmbh"),datasDt1);

    }

    /**
     * 启动指令入口
     *
     * @param paramData
     */
    private void qd(Map<String, Object> paramData) {

        Map<String, Object> map = new HashMap<>();

        RecordSet yszzRs = new RecordSet();
        String executeDept = (String) paramData.get("executeDept");
        if (executeDept != null && !executeDept.isEmpty()) {
            yszzRs.executeQuery("select * FROM uf_jccs_yszrzx WHERE yszrzxbm = ? ", executeDept);
            while (yszzRs.next()) {
                map.put("yszz", yszzRs.getString("id"));
            }
        }


        RecordSet ywlxRs = new RecordSet();
        RecordSet yskmRs = new RecordSet();
        String itemType = (String) paramData.get("itemType");
        if (itemType != null && !itemType.isEmpty()) {
            ywlxRs.executeQuery("select * FROM uf_jccs_ysxmywlx WHERE ysywlxbm = ?  ", itemType);
            while (ywlxRs.next()) {
                map.put("ywlx", ywlxRs.getString("id"));
            }
            yskmRs.executeQuery("SELECT yskmbm FROM uf_jccs_yskmysxmywl WHERE ysxmywlxbm = ? ", itemType);
            while (yskmRs.next()) {
                map.put("kmbm", yskmRs.getString("yskmbm"));
            }
        }

        RecordSet ywxlRs = new RecordSet();

        String itemDetail = (String) paramData.get("itemDetail");
        if (itemDetail != null && !itemDetail.isEmpty()) {
            ywxlRs.executeQuery("select * FROM uf_jccs_ysxmywlx WHERE ysywlxbm = ? ", itemDetail);
            while (ywxlRs.next()) {
                map.put("ywxl", ywxlRs.getString("id"));
            }

        }

        RecordSet xmbmRs = new RecordSet();
        String projectNumber = (String) paramData.get("projectNumber");
        if (projectNumber != null && !projectNumber.isEmpty()) {
            xmbmRs.executeQuery("select * FROM uf_ysxmdb WHERE xmbm = ?  ", projectNumber);
            while (xmbmRs.next()) {
                map.put("xmbh", xmbmRs.getString("id"));
            }
        }

        String currentDateString = TimeUtil.getCurrentDateString();
        String[] split = currentDateString.split("-");
        map.put("ysnd", Util.null2String(split[0]));
        map.put("sqdh", Util.null2String(paramData.get("requestNo")));
        map.put("sqsj", Util.null2String(paramData.get("requestTime")));
        map.put("xmmc", Util.null2String(paramData.get("projectName")));
        map.put("qbhhhyjyd", Util.null2String(paramData.get("signReportNum")));
        map.put("qbmchhyjyd", Util.null2String(paramData.get("signReportName")));
        map.put("xmzbrmc", Util.null2String(paramData.get("userName")));
        map.put("xmzbrgh", Util.null2String(paramData.get("userNumber")));
        map.put("xmqdsj", Util.null2String(paramData.get("startTime")));
        map.put("xmjssj", Util.null2String(paramData.get("endOfTime")));
        map.put("xmlxzjewy", Util.null2String(paramData.get("projectTotalAmount")));
        map.put("czfs", Util.null2String(paramData.get("investmentType")));
        map.put("ylzd", Util.null2String(paramData.get("attribute3")));
        map.put("qbfwdz", Util.null2String(paramData.get("signReportURL")));
        map.put("fafwdz", Util.null2String(paramData.get("optionURL")));
        map.put("gxsj", Util.null2String(paramData.get("updateDate")));
        logger.info("map:" + map);
        int workflowid = Integer.parseInt(createrequestMap.get("workflowid").toString());
        logger.info("workflowid=" + workflowid);
        String createrequest = Createrequest(workflowid, 2, createrequestMap.get("title").toString(), "1", map);
        logger.info("createrequest=" + createrequest + "...tableName:" + createrequestMap.get("tableName"));

        String sql = "select id from " + createrequestMap.get("tableName") + " where requestId = ? ";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql, createrequest);
        String id = null;
        while (rs.next()) {
            id = rs.getString("id");
        }


        addDt1(id);
        addDt2(id);
        return;
    }

    private void addDt2(String id) {


        JSONObject paramParams = JSONObject.parseObject(params.toString());
        JSONArray scene = paramParams.getJSONArray("scene");


        logger.info("id...:" + id + "...scene:" + scene);
        RecordSet rs = new RecordSet();
        if (!id.isEmpty()) {
            String sqlDt2 = "INSERT INTO " + createrequestMap.get("tableName") + "_dt2 (mainid,cjbm,cjmc,je)  VALUES (? ,?, ?, ?)";
            ArrayList<List> lists = new ArrayList<>();
            for (int i = 0; i < scene.size(); i++) {
                Map map = (Map) scene.get(i);
                ArrayList<String> list = new ArrayList<>();
                list.add(id);
                list.add(map.get("sceneNo").toString());
                list.add(map.get("sceneName").toString());
                list.add(map.get("proportion").toString());
                lists.add(list);
            }

            boolean b = rs.executeBatchSql(sqlDt2, lists);
            logger.info("增加第二个从表... flag=" + b + "数据lists=" + lists);
        }
    }

    private void addDt1(String id) {
        JSONObject paramParams = JSONObject.parseObject(params.toString());
        JSONArray product = paramParams.getJSONArray("product");


        logger.info("id...:" + id + "...product:" + product);
        RecordSet xmbmRs = new RecordSet();
        if (!id.isEmpty()) {
            String sqlDt1 = "INSERT INTO " + createrequestMap.get("tableName") + "_dt1 (mainid,xmbm,cp,je)  VALUES (? ,?, ?, ?)";
            ArrayList<List> lists = new ArrayList<>();
            for (int i = 0; i < product.size(); i++) {
                Map map = (Map) product.get(i);
                logger.info("map=" + map);
                ArrayList<String> list = new ArrayList<>();
                list.add(id);
                String projNo = Util.null2String(map.get("projNo"));
                if (projNo != null && !projNo.isEmpty()) {
                    xmbmRs.executeQuery("select * FROM uf_ysxmdb WHERE xmbm = ?  ", projNo);
                    while (xmbmRs.next()) {
                        list.add(Util.null2String(xmbmRs.getString("id")));
                    }
                }
                list.add(map.get("productName").toString());
                list.add(map.get("proportion").toString());
                lists.add(list);
                logger.info("list=" + list);
            }
            RecordSet rs = new RecordSet();
            boolean b = rs.executeBatchSql(sqlDt1, lists);
            logger.info("增加第一个从表... flag=" + b + "数据lists=" + lists);
        }
    }


    /**
     * 方法描述 : 创建流程方法
     *
     * @param workflowid
     * @param userid     创建人id
     * @param title      流程标题
     * @param IsNextFlow 是否默认流转到下一节点   1 是，0 否
     * @param map        数据map
     * @return String
     */
    public static String Createrequest(int workflowid, int userid, String title, String IsNextFlow, Map map) {
        Logger logger = LoggerFactory.getLogger();
        String newrequestid = "";
        RequestInfo req = new RequestInfo();
        req.setCreatorid(userid + "");  //创建人
        req.setWorkflowid(workflowid + "");//流程id
        req.setDescription(title);  //流程标题
        req.setIsNextFlow(IsNextFlow); //是否默认流转到下一节点
        MainTableInfo maintable = new MainTableInfo();
        Set<String> keySet = map.keySet();
        Property[] property = new Property[keySet.size()];
        int i = 0;
        Property p = null;
        for (String key : keySet) {
            p = new Property();
            p.setName(key);
            p.setValue(map.get(key).toString());
            property[i] = p;
            i++;
        }
        maintable.setProperty(property);

        req.setMainTableInfo(maintable);
        req.setRequestlevel("0");
        RequestService service = new RequestService();
        try {
            newrequestid = service.createRequest(req);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return newrequestid;
    }
}
